<template>
  <div class="iframe-container" :style="'height:'+ height">
    <iframe ref="iframe_ref" :src="openUrl" style="width: 100%;height: 100%; border: none; overflow-scrolling: auto;" />
  </div>
</template>

<script>
import { isExternal } from '@/utils/validate'

export default {
  props: {
    src: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      openUrl: '',
      height: document.documentElement.clientHeight + 'px;'
    }
  },
  watch: {
    $route(to, from) {
      this.refresh()
    }
  },
  created() {
    this.refresh()
  },
  mounted() {
    const that = this
    const iframe = this.$refs.iframe_ref
    window.onresize = function autoResize() {
      // that.height = document.documentElement.clientHeight + 'px;'
      if (iframe.contentDocument && iframe.contentDocument.body.offsetHeight) {
        iframe.height = iframe.contentDocument.body.offsetHeight
        that.height = iframe.height
      } else if (iframe.Document && iframe.Document.body.scrollHeight) {
        iframe.height = iframe.Document.body.scrollHeight
        that.height = iframe.height
      }
    }
    setInterval(function() {
      if (iframe.contentDocument && iframe.contentDocument.body.offsetHeight) {
        iframe.height = iframe.contentDocument.body.offsetHeight
        that.height = iframe.height
      } else if (iframe.Document && iframe.Document.body.scrollHeight) {
        iframe.height = iframe.Document.body.scrollHeight
        that.height = iframe.height
      }
    }, 500)
  },
  methods: {
    refresh() {
      if (this.src) {
        this.openUrl = this.src
      } else if (!isExternal(this.$route.path)) {
        if (this.$route.query.url) {
          this.openUrl = this.$route.query.url
        } else {
          this.openUrl = this.$store.state.app.server_api + this.$route.path
        }
      } else {
        this.openUrl = this.$route.path
      }
    }
  }
}
</script>
